package cn.com.websocket.service.impl;

import cn.com.websocket.handle.SocketHandle;
import cn.com.websocket.mapper.MessageMapper;
import cn.com.websocket.po.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.List;

/**
 * <p>历史消息消费策略</p>
 * */
@Service("historyMsgService")
public class HistoryMsgServiceImpl extends AbsMessageStrategy {

    @Autowired
    MessageMapper messageMapper;

    @Override
    public void handleMessage(Session session, Message message) {
        List<Message> cacheHistoryList = getCacheHistory(message.getSource(),message.getTarget());
        if(cacheHistoryList.isEmpty()){
            // 查看双方的聊天记录
            List<Message> sourceList  = messageMapper.getHistoryRecordBySourceWithTarget(message.getSource(),message.getTarget());
            List<Message> targetList  = messageMapper.getHistoryRecordBySourceWithTarget(message.getTarget(),message.getSource());
            putCacheHistory(message,sourceList,targetList);
            cacheHistoryList = mergeAndSort(sourceList,targetList);
        }
        Session sourceSession = SocketHandle.sessionPools.get(message.getSource());
        if(null==sourceSession){return;}
        if(cacheHistoryList.isEmpty()){return;}
        for(Message _msg:cacheHistoryList){
            sendMessage(sourceSession,_msg);
        }
    }
}
